import { StyleSheet, Text, View, ScrollView, Pressable, Image } from 'react-native';
import React, { useState, useMemo, useCallback } from 'react';
import { useFocusEffect } from '@react-navigation/native';
import { LineChart, CurveType } from 'react-native-gifted-charts';
import ECharts from 'react-native-echarts-pro';
import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';
import Icon from 'react-native-vector-icons/Ionicons';
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/en';
import { observer, deviceStore, userStore, appStore } from '~/store';
import { getHeartRateToday, sameMoment, historyHeart } from '~/api/deviceToolsApi';
import { px2dp, scale, width } from '~/utils/px2dp';
import { formatTimestamp } from '~/utils/formatDate';
import { ContentStatus } from '~/components';
interface Props {
    selectIndex: number;
}
export default observer((props: Props) => {
    dayjs.locale(appStore.app.language == 'zh' ? 'zh-cn' : 'en');
    const { selectIndex } = props;
    const { t } = useTranslation();
    const { userBindDeviceData, autoConnectDeviceSn } = userStore;
    const tableData = [
        { id: 1, title: t('HeartRateData.t1') },
        { id: 2, title: t('HeartRateData.t2') },
    ];
    const [activeIndex, setActiveIndex] = useState(1);
    const changeTable = (id) => {
        setActiveIndex(id);
        if (id == 1) {
            getHeartToday();
        } else {
            getHistory();
        }
    };

    const { device } = deviceStore;
    const deviceInfo = useMemo(() => {
        let res = userBindDeviceData.find((item) => item.device_sn == autoConnectDeviceSn);
        if (deviceStore.device?.connectedDeviceStatus == 1) {
            res = userBindDeviceData.find((item) => item.device_sn == device?.connectDevice?.device_sn);
        } else {
            if (autoConnectDeviceSn) {
                res = userBindDeviceData.find((item) => item.device_sn == autoConnectDeviceSn);
            } else {
                res = userBindDeviceData[0];
            }
        }
        return res;
    }, [
        userBindDeviceData,
        autoConnectDeviceSn,
        deviceStore.device?.connectedDeviceStatus,
        device?.connectDevice?.device_sn,
    ]);

    function indexToTime(index) {
        // 每份15分钟
        const minutes = index * 15;
        const h = String(Math.floor(minutes / 60)).padStart(2, '0');
        const m = String(minutes % 60).padStart(2, '0');
        return `${h}:${m}`;
    }
    function timeToIndex(time) {
        const [h, m] = time.split(':').map(Number); // 拆分并转数字
        return h * 4 + Math.floor(m / 15); // 1小时 = 4份15分钟
    }
    function roundToNearestQuarter() {
        const now = dayjs();
        const minutes = now.minute();
        const flooredMinutes = Math.floor(minutes / 15) * 15;
        return now.minute(flooredMinutes).second(0).format('HH:mm');
    }
    const [heartData, setHeartData] = useState({ time: '', value: 0 });
    const [chartData, setChartData] = useState<any[]>([]);
    const [sameTime, setSameTime] = useState('');
    const getHeartToday = () => {
        getHeartRateToday({
            deviceId: deviceInfo?.device_id,
            device_sn: deviceInfo?.device_sn,
        }).then((res) => {
            const result = res.returnData;
            if (Array.isArray(result)) {
                if (result.length === 0) {
                    setChartData([]);
                }
            } else if (result && typeof result === 'object') {
                const data = Object.entries(result).map(([index, value]) => {
                    return { time: indexToTime(Number(index)), value };
                });
                if (data.length > 0) {
                    const last: any = data[data.length - 1];
                    setHeartData(last);
                    const formattedData = data.map((item) => ({
                        value: item.value,
                        label: item.time,
                    }));
                    setChartData(formattedData);
                    const time = roundToNearestQuarter();
                    setSameTime(time);
                    const tag = timeToIndex(time);
                    getSameMoment(tag);
                }
            } else {
                setChartData([]);
            }
        });
    };

    const [sameData, setSameData] = useState([]);
    const getSameMoment = (point) => {
        const obj = { deviceId: deviceInfo.device_id, point, device_sn: deviceInfo.device_sn };
        sameMoment(obj).then((res) => {
            setSameData(res.returnData.sameMoment);
        });
    };

    // 历史心率数据
    const [historyList, setHistoryList] = useState([]);
    const [historyOther, setHistoryOther] = useState({
        guardHour: 0,
        gtCount: 0,
        calculation: { max: 0, avg: 0, min: 0 },
    });
    const getHistory = () => {
        historyHeart({ type: 1, deviceId: deviceInfo?.device_id, device_sn: deviceInfo?.device_sn }).then((res) => {
            if (res.code == 200) {
                const { list, other } = res.returnData;
                setHistoryOther(other);
                setHistoryList(list);
                const YData = list.map((item) => item.calculation.avg);
                const XData = list.map((item) => dayjs.unix(item.time).format('ddd')); // 转换成周几
                const echarts = createOption(XData, YData);
                setOption(echarts);
            }
        });
    };
    const [option, setOption] = useState({});
    const createOption = (xAxisData: string[], yAxisData: number[]) => ({
        title: {
            text: t('HeartRateData.t3') + '(BPM)',
            top: 10,
            left: 'center',
            textStyle: {
                color: '#fff',
                fontSize: 16,
            },
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLine: {
                lineStyle: {
                    color: '#ccc',
                    type: 'dashed',
                },
            },
            axisTick: { show: false },
            splitLine: {
                show: false,
                lineStyle: {
                    type: 'dashed',
                    color: '#e0e0e0',
                },
            },
        },
        tooltip: {
            trigger: 'axis',
        },
        yAxis: {
            type: 'value',
            axisLine: { show: true },
            axisTick: { show: false },
            splitLine: {
                show: false,
                lineStyle: {
                    type: 'dashed',
                    color: '#e0e0e0',
                },
            },
            max: 200,
            mine: 0,
        },
        grid: {
            left: '0%',
            right: '0%',
            top: '12%',
            bottom: '2%',
            containLabel: true,
        },
        series: [
            {
                data: yAxisData,
                smooth: 1,
                type: 'line',
                symbol: 'circle',

                itemStyle: {
                    normal: {
                        color: '#02675f',
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [
                                    {
                                        offset: 0,
                                        color: '#01806f', // 0% 处的颜色
                                    },
                                    {
                                        offset: 0.5,
                                        color: '#025f5a', // 50% 处的颜色
                                    },
                                    {
                                        offset: 1,
                                        color: '#04122a', // 100% 处的颜色
                                    },
                                ],
                                global: false, // 缺省为 false
                            },
                        },
                        smooth: true,
                    },
                },
            },
        ],
    });
    useFocusEffect(
        useCallback(() => {
            if (selectIndex == 2) {
                getHeartToday();
            }
            getHistory();
        }, [selectIndex, deviceInfo]),
    );

    return (
        <ScrollView contentContainerStyle={styles.contentStyle} showsVerticalScrollIndicator={false}>
            <View style={[styles.nav, styles.row, styles.between]}>
                <View>
                    <Text style={styles.title}>{t('HeartRateData.t4')}</Text>
                    <Text style={styles.heartValue}>{heartData.value}</Text>
                </View>
                <View>
                    <View style={[styles.row, styles.between]}>
                        {tableData.map((item: any, index) => {
                            return (
                                <Pressable
                                    onPress={() => changeTable(item.id)}
                                    key={index}
                                    style={[
                                        styles.listTable,
                                        activeIndex === item.id && { backgroundColor: 'rgba(216, 216, 216, 0.32)' },
                                    ]}>
                                    <Text
                                        style={[
                                            styles.listTableText,
                                            activeIndex === item.id && { fontWeight: 'bold', color: '#000' },
                                        ]}>
                                        {item?.title}
                                    </Text>
                                </Pressable>
                            );
                        })}
                    </View>
                </View>
            </View>
            {activeIndex == 1 ? (
                <View>
                    <LineChart
                        data={chartData}
                        width={width - px2dp(120)}
                        height={px2dp(500)}
                        color="#01806f"
                        thickness={2}
                        curved
                        dataPointsHeight={16} // 合理范围 6~20
                        dataPointsWidth={16}
                        dataPointsColor="#01806f"
                        xAxisLabelTextStyle={{ color: '#d4d4d4', fontSize: px2dp(24) }}
                        yAxisTextStyle={{ color: '#d4d4d4', fontSize: px2dp(24) }}
                        hideRules // 不显示背景网格线
                        xAxisColor="#d4d4d4"
                        yAxisColor="#d4d4d4"
                        hideYAxisText={false}
                        areaChart
                        startFillColor="#01806f" // 顶部渐变色
                        startOpacity={0.8}
                        endFillColor="#04122a" // 底部渐变色
                        endOpacity={0.2}
                        curveType={CurveType.QUADRATIC}
                        onPress={(res) => {
                            const tag = timeToIndex(res.label);
                            setSameTime(res.label);
                            getSameMoment(tag);
                        }}
                    />
                    <View style={styles.card}>
                        <View style={[{ marginBottom: px2dp(32) }]}>
                            <Text style={styles.t1}>{t('HeartRateData.t5')}</Text>
                            {sameTime && (
                                <Text style={[styles.t2, { marginTop: px2dp(12) }]}>
                                    {t('HeartRateData.t6')}：{sameTime}
                                </Text>
                            )}
                        </View>
                        <View>
                            {sameData.length > 0 ? (
                                <>
                                    {sameData.map((item: any, index) => {
                                        const width = item.value === 0 ? 0 : (item.value / 200) * 200;
                                        return (
                                            <Pressable key={index} style={[styles.list, styles.row]}>
                                                <Text style={styles.time}>{formatTimestamp(item.timeStamp)}</Text>
                                                <View style={[styles.heartContent, styles.row]}>
                                                    <View style={[styles.bar, { width }]} />
                                                    <Text style={styles.heart}>
                                                        {item.value > 0 ? item.value + 'bpm' : t('HeartRateData.t7')}
                                                    </Text>
                                                </View>
                                            </Pressable>
                                        );
                                    })}
                                </>
                            ) : (
                                <>
                                    <ContentStatus status="empty" />
                                </>
                            )}
                        </View>
                    </View>
                </View>
            ) : (
                <View>
                    <View style={{ width: width, height: px2dp(600) }}>
                        <ECharts width={width} option={option} height={px2dp(600)} />
                    </View>
                    <View style={[styles.card]}>
                        <Text style={styles.title}>{t('HeartRateData.t8')}</Text>
                        <View style={[styles.row, { marginTop: px2dp(14), flexWrap: 'wrap' }]}>
                            <View style={[styles.listItem]}>
                                <Text style={styles.t2}>{t('HeartRateData.t9')}</Text>
                                <View style={[styles.row, { marginTop: px2dp(12) }]}>
                                    <Text style={styles.heartValue}>{historyOther?.calculation?.min || '-'}</Text>
                                    <Text style={styles.t4}>bpm</Text>
                                </View>
                            </View>
                            <View style={[styles.listItem]}>
                                <Text style={styles.t2}>{t('HeartRateData.t10')}</Text>
                                <View style={[styles.row, { marginTop: px2dp(12) }]}>
                                    <Text style={styles.heartValue}>{historyOther?.calculation?.avg || '-'}</Text>
                                    <Text style={styles.t4}>bpm</Text>
                                </View>
                            </View>
                            <View style={[styles.listItem]}>
                                <Text style={styles.t2}>{t('HeartRateData.t11')}</Text>
                                <View style={[styles.row, { marginTop: px2dp(12) }]}>
                                    <Text style={styles.heartValue}>{historyOther?.calculation?.max || '-'}</Text>
                                    <Text style={styles.t4}>bpm</Text>
                                </View>
                            </View>
                            <View style={[styles.listItem]}>
                                <Text style={styles.t2}>{t('HeartRateData.t12')}</Text>
                                <View style={[styles.row, { marginTop: px2dp(12) }]}>
                                    <Text style={styles.heartValue}>{historyOther?.gtCount || 0}</Text>
                                    <Text style={styles.t4}>{t('HeartRateData.t13')}</Text>
                                </View>
                            </View>
                            <View style={[styles.listItem]}>
                                <Text style={styles.t2}>{t('HeartRateData.t14')}</Text>
                                <View style={[styles.row, { marginTop: px2dp(12) }]}>
                                    <Text style={styles.heartValue}>{historyOther?.guardHour || 0}</Text>
                                    <Text style={styles.t4}>{t('HeartRateData.t15')}</Text>
                                </View>
                            </View>
                        </View>
                    </View>
                    <View style={styles.card}>
                        {historyList.map((item: any, index) => {
                            return (
                                <View style={styles.historyItem} key={index}>
                                    <Text style={styles.historyTime}>{formatTimestamp(item.time)}</Text>
                                    <View style={[styles.row, styles.between, { marginTop: px2dp(24) }]}>
                                        <Image
                                            style={styles.icons}
                                            source={{ uri: 'https://line.shbjy.cn//wxdata/imgs/heart.png' }}
                                        />
                                        <View style={[styles.row]}>
                                            <Icon name="arrow-up-outline" size={px2dp(40)} color={'#a4a4a4'}></Icon>
                                            <Text style={styles.t5}>
                                                {t('HeartRateData.t16')}：{item?.calculation?.max}BPM
                                            </Text>
                                        </View>
                                        <View style={[styles.row]}>
                                            <Icon name="arrow-down-outline" size={px2dp(40)} color={'#a4a4a4'}></Icon>
                                            <Text style={styles.t5}>
                                                {t('HeartRateData.t17')}：{item?.calculation?.min}BPM
                                            </Text>
                                        </View>
                                    </View>
                                </View>
                            );
                        })}
                    </View>
                </View>
            )}
        </ScrollView>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    contentStyle: {
        flexGrow: 1,
        paddingBottom: '50%',
        // paddingHorizontal: px2dp(24),
    },
    nav: {
        marginHorizontal: px2dp(24),
        marginVertical: px2dp(32),
    },
    title: {
        color: '#fff',
        fontSize: scale(24),
        fontWeight: 'bold',
        marginBottom: px2dp(12),
    },
    heartValue: {
        color: '#fff',
        fontSize: scale(50),
    },
    card: {
        marginHorizontal: px2dp(24),
        marginTop: px2dp(32),
        borderWidth: 1,
        padding: px2dp(24),
        borderRadius: px2dp(24),
        borderColor: 'rgba(255, 255, 255, 0.12)',
    },
    time: {
        color: '#d4d4d4',
        fontSize: scale(28),
    },
    list: {
        marginBottom: px2dp(32),
    },
    heart: {
        color: '#a4a4a4',
        fontSize: scale(28),
    },
    t1: {
        color: '#ffff',
        fontSize: scale(28),
    },
    t2: {
        color: '#a4a4a4',
        fontSize: scale(28),
    },
    heartContent: {
        marginLeft: px2dp(24),
    },
    bar: {
        height: px2dp(20),
        backgroundColor: '#01806f',
        borderRadius: px2dp(10),
        marginRight: px2dp(14),
    },
    listTable: {
        height: px2dp(60),
        justifyContent: 'center',
        alignItems: 'center',
        paddingHorizontal: px2dp(12),
        borderRadius: px2dp(12),
        width: px2dp(120),
    },
    listTableText: {
        color: '#fff',
        fontSize: scale(28),
    },
    listItem: {
        width: (width - px2dp(100)) / 3,
        marginBottom: px2dp(32),
        justifyContent: 'center',
        alignItems: 'center',
    },
    t4: {
        color: '#d4d4d4',
        fontSize: scale(24),
        marginLeft: px2dp(8),
    },
    historyItem: {
        marginBottom: px2dp(32),
    },
    historyTime: {
        color: '#fff',
        fontSize: scale(28),
    },
    icons: {
        width: px2dp(50),
        height: px2dp(50),
    },
    t5: {
        color: '#fff',
        fontSize: scale(28),
    },
});
